package toOffer;

/**
 * <h3>leetcode</h3>
 *
 * @author YuanAo
 * @date 2024/4/29 15:58
 * @description <p>三数之和</p>
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 题目：给定一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a ，b ，c ，
 * 使得 a + b + c = 0 ？请找出所有和为 0 且 不重复 的三元组。
 */
public class LCR007 {
    public static void main(String[] args) {
//        nums = [-1,0,1,2,-1,-4]
//        输出：[[-1,-1,2],[-1,0,1]]

        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = threeSum(nums);
        for (List<Integer> list : lists) {
            for (Integer integer : list) {
                System.out.print(integer + " ");
            }
        }

    }

    /**
     * [-4, -1, -1, 0, 1, 2]
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum(int[] nums) {

        Arrays.sort(nums);
        if (nums[0] > 0 || nums.length < 3){
            return null;
        }

        ArrayList<List<Integer>> resultList = new ArrayList<>();
        ArrayList<Integer> newList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            newList = newArr(i, nums);
            List<Integer> list = getList(newList, nums[i]);
            resultList.add(list);
        }

        return resultList;
    }

    /**
     * 去除nums[]数组中序号为index的数，返回一个Arraylist<integer>类型的数据
     *
     * @param index
     * @param nums
     * @return
     */
    public static ArrayList<Integer> newArr(int index, int[] nums) {

        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (i == index) {
                break;
            } else {
                list.add(nums[i]);
            }
        }
        return list;
    }

    /**
     * 获取数组里和等于target的两个数
     *
     * @param newArr
     * @param target
     * @return
     */
    public static List<Integer> getList(ArrayList<Integer> newArr, int target) {
        List<Integer> list = new ArrayList<>();

        int left = 0;
        int right = newArr.size() - 1;
        while (left < right) {
            if (newArr.get(left) + newArr.get(right) == target) {
                list.add(target);
                list.add(left);
                list.add(right);
                break;
            } else if (newArr.get(left) + newArr.get(right) > target) {
                right--;
            } else {
                left++;
            }
        }

        return list;
    }

}
